<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 后台管理</title>
    <link rel="stylesheet" href="/static/base.css">
    <link rel="stylesheet" href="/static/components.css">
    <link rel="stylesheet" href="/static/pages.css">
    <link rel="stylesheet" href="/static/admin/admin.css">
    <script src="/static/lib/js/vue.global.js"></script>
    <script src="/static/lib/js/axios.min.js"></script>
</head>
<body>
  <div class="admin-layout">
    <div class="admin-header">
      <h2>用户管理</h2>
      <div>
        <button class="btn" onclick="location.href='/'">返回前台</button>
        <button class="btn" onclick="logout()">退出</button>
      </div>
    </div>

    <div class="admin-main">
      <!-- 左侧导航（公共组件注入） -->
      <div class="admin-sidebar"></div>

      <div class="admin-content">
        <div class="content-page active" id="app">
          <h3>用户管理</h3>
          <p class="page-description">管理系统用户账户</p>

          <div class="search-box">
            <input type="text" v-model="searchKeyword" @input="searchUsers" placeholder="搜索昵称或手机号..." class="search-input">
            <button @click="showAddModal" class="btn btn-primary">新增用户</button>
          </div>

          <div class="performance-table">
            <div v-if="loading" class="loading-state">加载中...</div>
            <div v-else-if="users.length === 0" class="empty-state">暂无用户数据</div>
            <table v-else>
              <thead>
                <tr>
                  <th>ID</th>
                  <th>昵称</th>
                  <th>手机号</th>
                  <th>创建时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in users" :key="user.id">
                  <td>{{ user.id }}</td>
                  <td>{{ user.nickname }}</td>
                  <td>{{ user.phone }}</td>
                  <td>{{ formatDate(user.created_at) }}</td>
                  <td>
                    <button @click="editUser(user)" class="btn btn-primary">编辑</button>
                    <button @click="deleteUser(user.id)" class="btn btn-danger">删除</button>
                  </td>
                </tr>
              </tbody>
            </table>
          </div>

          <div v-if="showModal" class="modal-overlay" @click="closeModal">
            <div class="modal-content" @click.stop>
              <h3>{{ editingUser ? '编辑用户' : '新增用户' }}</h3>
              <form @submit.prevent="saveUser">
                <div class="form-group">
                  <label>昵称:</label>
                  <input type="text" v-model="userForm.nickname" required>
                </div>
                <div class="form-group">
                  <label>手机号:</label>
                  <input type="text" v-model="userForm.phone" required>
                </div>
                <div class="form-group">
                  <label>密码:</label>
                  <input type="password" v-model="userForm.password" :required="!editingUser">
                </div>
                <div class="form-actions">
                  <button type="submit" class="btn btn-primary">保存</button>
                  <button type="button" @click="closeModal" class="btn">取消</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <style>
    .search-box { background: white; padding: 20px; border-radius: 8px; margin-bottom: 20px; }
    .search-input { width: 300px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin-right: 10px; }
    .performance-table { background: white; border-radius: 8px; overflow: hidden; margin-bottom: 20px; }
    .performance-table table { width: 100%; border-collapse: collapse; }
    .performance-table th, .performance-table td { padding: 12px; text-align: left; border-bottom: 1px solid #eee; }
    .performance-table th { background: #f8f9fa; font-weight: 600; }
    .modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); display: flex; align-items: center; justify-content: center; z-index: 1000; }
    .modal-content { background: white; padding: 30px; border-radius: 8px; min-width: 400px; }
    .form-group { margin-bottom: 15px; }
    .form-group label { display: block; margin-bottom: 5px; font-weight: 600; }
    .form-group input { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; }
    .form-actions { display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px; }
    .loading-state, .empty-state { text-align: center; padding: 40px; color: #6c757d; }
  </style>

  <script src="/static/admin/components/sidebar.js"></script>
  <script>
    window.addEventListener('load', function() {
      if (typeof Vue !== 'undefined') {
        const { createApp } = Vue;
        createApp({
          data() {
            return {
              users: [],
              searchKeyword: '',
              showModal: false,
              editingUser: null,
              userForm: { nickname: '', phone: '', password: '' },
              loading: false
            }
          },
          mounted() {
            this.loadUsers();
            // 注入公共侧边栏
            injectAdminSidebar('/admin/user/user-management');
          },
          methods: {
            async loadUsers() {
              this.loading = true;
              try {
                const response = await axios.get(`/admin/api/user/list?search=${this.searchKeyword}`);
                if (response.data.success) {
                  this.users = response.data.users;
                }
              } catch (error) {
                console.error('加载用户列表失败:', error);
                alert('加载用户列表失败');
              } finally {
                this.loading = false;
              }
            },
            searchUsers() {
              this.loadUsers();
            },
            showAddModal() {
              this.editingUser = null;
              this.userForm = { nickname: '', phone: '', password: '' };
              this.showModal = true;
            },
            editUser(user) {
              this.editingUser = user;
              this.userForm = { nickname: user.nickname, phone: user.phone, password: '' };
              this.showModal = true;
            },
            closeModal() {
              this.showModal = false;
              this.editingUser = null;
              this.userForm = { nickname: '', phone: '', password: '' };
            },
            async saveUser() {
              try {
                if (this.editingUser) {
                  await axios.put(`/admin/api/user/${this.editingUser.id}`, this.userForm);
                  alert('用户更新成功');
                } else {
                  await axios.post('/admin/api/user', this.userForm);
                  alert('用户创建成功');
                }
                this.closeModal();
                this.loadUsers();
              } catch (error) {
                console.error('保存用户失败:', error);
                alert('保存用户失败');
              }
            },
            async deleteUser(userId) {
              if (confirm('确定要删除这个用户吗？')) {
                try {
                  await axios.delete(`/admin/api/user/${userId}`);
                  alert('用户删除成功');
                  this.loadUsers();
                } catch (error) {
                  console.error('删除用户失败:', error);
                  alert('删除用户失败');
                }
              }
            },
            formatDate(dateString) {
              if (!dateString) return '-';
              const date = new Date(dateString);
              return date.toLocaleDateString('zh-CN');
            },
            async logout() {
              try {
                await fetch('/admin/logout', { method: 'POST' });
                location.href = '/admin/login';
              } catch (e) {
                location.href = '/admin/login';
              }
            }
          }
        }).mount('#app');
      } else {
        document.getElementById('app').innerHTML = '<div style="text-align: center; padding: 40px; color: red;">Vue.js 加载失败</div>';
      }
    });
  </script>
</body>
</html>
